package cn.jly.bigdata.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * @author lanyangji
 * @date 2019/12/5 21:40
 */
object SparkStreaming08_SparkWindow {

  def main(args: Array[String]): Unit = {

    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming08_SparkWindow")
    val streamingContext = new StreamingContext(sparkConf, Seconds(5))

    // 监控端口并读取端口数据
    val socketDStream: ReceiverInputDStream[String] = streamingContext.socketTextStream("hadoop102", 9999)

    socketDStream
      .flatMap(_.split(" "))
      .map((_, 1))
      .reduceByKeyAndWindow(
        (x: Int, y: Int) => x + y,
        Seconds(10), // 窗口大小
        Seconds(5) // 步长
      )
      .print()

    // 启动
    streamingContext.start()
    streamingContext.awaitTermination()
  }
}
